<template>
  <div id="app">
    <!--主体容器-->
    <div class="contains" style="padding-bottom: 10px">
      <!--搜索栏-->
      <ul class="search-bar clearfix">
        <li class="search-item clearfix">
          <label>选择日期：</label>
          <div class="search-box">
            <input id="dateRange" ref="dateRange" type="text" class="common-text large" placeholder="日期范围" />
          </div>
        </li>
        <li class="search-item">
          <input class="common-button" type="button" value="查询" @click="searchData('search')" />
        </li>
        <li class="search-item">
          <input class="default-button" type="button" value="导出" @click="exportData()" />
        </li>
      </ul>
      <!--图表展示-->
      <div ref="myChart" class="overview-chart"></div>
    </div>
  </div>
</template>

<script>
// import laydate from "laydate";
import { formarTime, getQueryVariable, export2Excel } from '../../js/utils.js'

// laydate.render({
//   elem: "#dateRange",
//   type: "datetime",
//   range: "~",
// });

export default {
  name: 'CommonChart',
  data() {
    return {
      excelTitle: [
        { title: '时间戳', key: 'timesTamp' },
        { title: '总场', key: 'totalField' },
        { title: '磁偏角', key: 'magneticAngle' },
        { title: '磁倾角', key: 'magneticInclination' },
        { title: '北向分量', key: 'northboundComponent' },
        { title: '东向分量', key: 'verticalComponents' },
        { title: '垂直分量', key: 'sastorientedComponent' }
      ],
      types: {
        zc: {
          name: '总场',
          velName: '总\n场',
          value: 'totalField',
          unit: 'nT'
        },
        pj: {
          name: '偏角',
          velName: '偏\n角',
          value: 'magneticAngle',
          unit: '°(度)'
        },
        qj: {
          name: '倾角',
          velName: '倾\n角',
          value: 'magneticInclination',
          unit: '°(度)'
        },
        xfl: {
          name: 'X分量',
          velName: 'X\n分\n量',
          value: 'northboundComponent',
          unit: 'nT'
        },
        yfl: {
          name: 'Y分量',
          velName: 'Y\n分\n量',
          value: 'verticalComponents',
          unit: 'nT'
        },
        zfl: {
          name: 'Z分量',
          velName: 'Z\n分\n量',
          value: 'sastorientedComponent',
          unit: 'nT'
        }
      },
      // currentIns: '',
      // instruments: [],
      pageData: {
        mode: 'default',
        title: '',
        name: '',
        velName: '',
        value: '',
        unit: ''
      },
      dataList: [],
      myChart: null,
      interval: null
    }
  },
  // 自定义方法
  methods: {
    // 初始化
    init() {
      var that = this
      if (sessionStorage.getItem('currentIns')) {
        that.currentIns = JSON.parse(sessionStorage.getItem('currentIns')).equipmentName
      }

      // console.log(getQueryVariable('name'));
      if (getQueryVariable()) {
        var title = getQueryVariable()
        // console.log(title)
        this.pageData.title = title
        // console.log(this.pageData.title)
        // console.log(this.types[title].name)
        // console.log(this.types[title].velName)
        // console.log(this.types[title].value)
        // console.log(this.types[title].unit)
        this.pageData.name = this.types[title].name
        this.pageData.velName = this.types[title].velName
        this.pageData.value = this.types[title].value
        this.pageData.unit = this.types[title].unit
      } else {
        this.pageData.title = ''
        this.pageData.name = ''
        this.pageData.velName = ''
        this.pageData.value = ''
        this.pageData.unit = ''
      }
      var now = new Date()
      var date = {
        year: now.getFullYear(), // 年
        month: now.getMonth() + 1 < 10 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1, // 月
        day: now.getDate() < 10 ? '0' + now.getDate() : now.getDate(), // 日
        hour: now.getHours() < 10 ? '0' + now.getHours() : now.getHours(), // 时
        minute: now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes(), // 分
        second: now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds() // 秒
      }
      document.getElementById('dateRange').value = date.year + '-' + date.month + '-' + date.day + ' 00:00:00' + ' ~ ' + date.year + '-' + date.month + '-' + date.day + ' 23:59:59'

      this.myChart = this.$echarts.init(this.$refs.myChart)
      this.searchData(this.pageData.mode)
      // 加上定时，会导致查询框输入时间后，不用点击查询按钮就能自动刷新
      // this.interval = setInterval(function () {
      //   that.searchData(that.pageData.mode)
      // }, 5000)
    },

    // 查询
    searchData(mode) {
      // console.log(mode);
      // 通过axios请求数据的坑：
      // 因为用了 function 函数 的原因，在函数里面，this是指向函数本身，已经不是外部的默认this了
      // 使用一个 that 指向 外部的this ，将值传进data中，然后调用 that.tableData
      var that = this
      this.pageData.mode = mode
      // console.log(this.$refs.dateRange.value)
      if (this.$refs.dateRange.value === '') {
        this.$message.warning('请选择日期！')
      } else {
        var dateRange = this.$refs.dateRange.value.split(' ~ ')
        // console.log(dateRange)
        this.$http({
          method: 'post',
          url: '/finddata',
          data: {
            startDate: dateRange[0],
            endDate: dateRange[1]
          }
        })

          // 采用箭头函数就不会存在this指向问题
          // .then((res) => {
          //   // console.log(res);
          //   if (res.data && res.data.code === 200) {
          //     console.log(res.data.data)
          //     this.dataList = res.data.data
          //     this.initChart(mode, res.data.data)
          //   } else {
          //     this.$message.warning(res.data.msg)
          //   }
          // })
          // .catch(function (err) {
          //   console.log(err)
          // })

          .then(function (res) {
            // console.log(res);
            if (res.data && res.data.code === 200) {
              console.log(res.data.data)
              that.dataList = res.data.data
              // console.log(that.dataList)
              // console.log(that.dataList)
              that.initChart(mode, res.data.data)
            } else {
              that.$message.warning(res.data.msg)
            }
          })
          .catch(function (err) {
            console.log(err)
          })
      }
    },

    // 导出(虽所使用的mock数据库相同，但避免不查询时使用导出而无dataList的情况)
    exportData() {
      var that = this
      // console.log(this.$refs.dateRange.value);
      if (this.$refs.dateRange.value === '') {
        this.$message.warning('请选择日期！')
      } else {
        var dateRange = this.$refs.dateRange.value.split(' ~ ')
        let excelName = dateRange[0] + ' - ' + dateRange[1]
        this.$http({
          method: 'post',
          url: '/exportexcel',
          data: {
            startDate: dateRange[0],
            endDate: dateRange[1]
          }
        }).then(function (res) {
          // console.log(res)
          if (res.data && res.data.code === 200) {
            that.dataList = res.data.data
            console.log(that.dataList)
            export2Excel(that.excelTitle, that.dataList, excelName)
          } else {
            that.$message.warning(res.data.msg)
          }
        })
      }
    },

    // 初始化图表
    initChart: function (mode, data) {
      console.log(data.length)
      // console.log(mode)
      var that = this,
        date = [],
        begin = 0,
        list = []
      if (mode === 'default') {
        // 默认
        if (data.length > 360) {
          begin = data.length - 360
        } else {
          begin = 0
        }
      } else if (mode === 'search') {
        begin = 0
      }
      for (var i = begin; i < data.length; i++) {
        // console.log(data[i]);
        date.push(formarTime(data[i].timesTamp))
        list.push(data[i][that.pageData.value])
      }
      // console.log(date, list);
      // console.log(list.length);
      this.myChart.setOption({
        title: {
          text: that.pageData.velName,
          backgroundColor: '#D8E2FB',
          borderColor: '#000',
          borderWidth: 0.5,
          borderRadius: 5,
          top: '30%',
          left: 10,
          textAlign: 'center',
          textStyle: {
            fontWeight: 'normal',
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          top: 30,
          right: 10,
          bottom: 50,
          left: 30,
          containLabel: true
        },
        xAxis: {
          data: date
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            // 使其坐标轴数据保留至有效数字位
            formatter: function (value) {
              if (that.pageData.velName == '偏\n角') {
                return value.toFixed(4)
              } else if (that.pageData.velName == '倾\n角') {
                return value.toFixed(4)
              } else {
                return value.toFixed(2)
              }
            }
          },
          name: '单位：' + that.pageData.unit,
          min: function (value) {
            return value.min
          },
          max: function (value) {
            return value.max
          }
        },
        dataZoom: [
          {
            type: 'slider',
            start: 1,
            end: 100
          }
        ],
        series: {
          name: that.pageData.name,
          type: 'line',
          smooth: true,
          data: list
        }
      })
    }
  },
  // 实例创建完成
  created() {
    // this.getData()
  },
  // 模板编译完成
  mounted() {
    this.init()
  },
  // 数据更新完毕
  updated() {
    // console.log('数据更新完毕');
  },
  // 实例销毁完成
  destroyed() {
    clearInterval(this.interval)
  }
}
</script>

<style></style>
